﻿using System;
using System.Collections;
using System.Collections.Generic;
using Unity.UIWidgets.animation;
using UnityEngine;
using UnityEngine.Animations;

public class CharacterActControl : MonoBehaviour
{
    private CharacterController characterController;
    private Animator animaControl;

    private bool canJump = true;

    [SerializeField] private float speed = 2f;

    [SerializeField] private float rotateSpeed = 90f;

    // Start is called before the first frame update
    void Start()
    {
        characterController = GetComponent<CharacterController>();
        animaControl = GetComponent<Animator>();
    }

    private void FixedUpdate()
    {
        float vertical = Input.GetAxis("Vertical");
        float horizontal = Input.GetAxis("Horizontal");
        
        if (Math.Abs(horizontal) > 0)
        {
            transform.Rotate(transform.up * horizontal * rotateSpeed * Time.deltaTime);
            characterController.SimpleMove(transform.forward * horizontal * speed);
        }
        PlayAnima(vertical, horizontal);
    }

    private float moveOffset;
    private float rotateOffset;
    void PlayAnima(float vertical, float horizontal)
    {
        bool isMoving = Mathf.Abs(vertical) > 0 || Mathf.Abs(horizontal) > 0;
        animaControl.SetBool("isMove", isMoving);
        if (isMoving)
        {
            if (vertical > 0) moveOffset = Mathf.Min(10, moveOffset + 1f);
            else  moveOffset = Mathf.Max(0, moveOffset - 1f);

            if (horizontal > 0) rotateOffset = Mathf.Min(10, rotateOffset + 1f);
            else if (horizontal < 0) rotateOffset = Mathf.Max(-10, rotateOffset - 1f);
            else
            {
                if (rotateOffset < 0)
                {
                    rotateOffset = Mathf.Min(0, rotateOffset + 1f);
                }
                else
                {
                    rotateOffset = Mathf.Max(0, rotateOffset - 1f);
                }
            }
        }
        else
        {
            moveOffset = Mathf.Max(0, moveOffset - 1f);
            if (rotateOffset < 0)
            {
                rotateOffset = Mathf.Min(0, rotateOffset + 1f);
            }
            else
            {
                rotateOffset = Mathf.Max(0, rotateOffset - 1f);
            }
        }

        animaControl.SetFloat("move_veco", moveOffset);
        animaControl.SetFloat("move_dire", rotateOffset);

        characterController.SimpleMove(transform.forward * vertical * (speed + moveOffset / 5));
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
